package com.chen.spikemall.mq;

import com.chen.spike.model.PostOrder;
import com.chen.spike.model.PostOrderResp;
import com.chen.spikemall.exception.NoInventoryException;
import com.chen.spikemall.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "order-request-queue")
public class OrderMqServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(OrderMqServiceImpl.class);

    @Autowired
    OrderService orderService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @RabbitHandler
    public void onMessage(@Payload PostOrder postOrder) {

        logger.info("receive request : " + postOrder);
        try {
            String orderNO = orderService.createOrder(postOrder.getAccount(), postOrder.getGoodsNo());

            logger.info("generate orderNO :" + orderNO);

            PostOrderResp postOrderResp = new PostOrderResp();
            postOrderResp.setAccount(postOrder.getAccount());
            postOrderResp.setGoodsNo(postOrder.getGoodsNo());
            postOrderResp.setOrderNo(orderNO);



            rabbitTemplate.convertAndSend("order-resp-queue", postOrderResp);

            logger.info("SEND MQ orderNO :" + postOrderResp);
        } catch (NoInventoryException e) {
            e.printStackTrace();
        }

    }

}
